package edu.umd.ion.wavemeter.server;

import java.io.IOException;

import jd2xx.JD2XX;
import jd2xx.JD2XXOutputStream;


public class FiberSwitcher {
	int CurrentChannel = -1;
	String Devicename;
	JD2XX jd = new JD2XX();
	JD2XXOutputStream outputStream; 
	byte[] Buffer = { 'c', 'h', '0', 0x0D, 0x0A };

	public FiberSwitcher( String devicename )  {
		try {
			Devicename = devicename;
			jd.openByDescription(devicename);
			jd.setBaudRate(115200);
			jd.setDataCharacteristics( 8, JD2XX.STOP_BITS_1, JD2XX.PARITY_NONE );
			jd.setFlowControl( JD2XX.FLOW_NONE, 0, 0 );
			jd.setTimeouts(1000, 1000);
			outputStream = new JD2XXOutputStream(jd);
			System.out.println("Fiberswitch "+devicename+" opened successfully.");
		}
		catch (IOException ex) {
			System.out.println("Opening of Fiberswitch "+devicename+" failed.");
		}
	}
	
	public void setChannel(int channel) {
		CurrentChannel = channel;
		//System.out.println("Switch to Channel "+channel);
		Buffer[2] =  (byte) ( 0x30 +  channel);
		try {
			outputStream.write(Buffer);
			outputStream.flush();
		}
		catch (IOException ex) {
			
		}
	}
	
	public int getChannel() {
		return CurrentChannel;
	}
	
	public void close() {
		try {
		outputStream.close();
		jd.close();
		}
		catch (IOException ex) {
			
		}
	}
}
